package top100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Godc
 * @description
 */
public class Permute {
    public static void main(String[] args) {
        PathSumSolution s = new PathSumSolution();
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(3);
        TreeNode node3 = new TreeNode(4);
        root.left = node1;
        root.right = node2;
        node1.left = node3;
        s.pathSum(root,7);

    }
}
class PermuteSolution {
    List<Integer> list = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        int[] visited = new int[nums.length];
        dfs(nums,visited,0);
        return res;
    }
    public void dfs(int[] nums,int[] visited,int depth){
        if(depth==nums.length){
            res.add(new ArrayList<>(list));
        }
        for(int i = 0;i<nums.length;i++){
            if(visited[i]==0){
                visited[i] = 1;
                list.add(nums[i]);
                dfs(nums,visited,depth+1);
                visited[i] = 0;
                list.remove(depth);
            }
        }
    }
}
class PathSumSolution {
    List<List<Integer>> res = new ArrayList();
    LinkedList<Integer> path = new LinkedList();
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        dfs(root,targetSum,0);
        return res;
    }
    public void dfs(TreeNode root,int targetSum,int sum){
        if(root==null) return;
        sum+=root.val;
        path.add(root.val);
        if(root.left==null&&root.right==null){
            if(sum==targetSum){
                res.add(new ArrayList<>(path));
            }
            return;
        }
        dfs(root.left,targetSum,sum);
        dfs(root.right,targetSum,sum);
        path.removeLast();
    }
}